#include "CTableTrigger.h"

CTableTrigger::CTableTrigger(QObject *parent) : AbsTable("trigger",parent)
{
    if(!this->exisit())
        createTable();

    columnNames();
}

CTableTrigger *CTableTrigger::instance()
{
    static CTableTrigger *pInstance = nullptr;
    if(nullptr == pInstance){
        pInstance = new CTableTrigger();
    }

    return pInstance;
}

bool CTableTrigger::createTable()
{
    QString strSql =    "CREATE TABLE [trigger] (            "
                        "    id         CHAR (50) PRIMARY KEY"
                        "                         UNIQUE     "
                        "                         NOT NULL,  "
                        "    session_id TEXT,                "
                        "    conditions TEXT,                "
                        "    reply      TEXT,                "
                        "    is_hex     BLOB                 "
                        ");                                  ";

    return execSql(strSql);
}

bool CTableTrigger::deleteSession(QString strSessionId)
{
    QString strSql = QString("delete from %1 where session_id='%2'").arg(m_strTableName,strSessionId);

    QSqlQuery query(*dbConnection());
    query.prepare(strSql);

    return exec(query);
}

bool CTableTrigger::addRows(QVector<StTrigger> &vecRows)
{
    transaction();
    foreach(StTrigger st,vecRows){
        QString strSql = "insert into " + m_strTableName + " values(";
        for(int i = 0; i < m_strListColumnNames.count(); i++){
            strSql += "?,";
        }
        strSql.chop(1); //删除最后一个字符
        strSql += ")";

        QSqlQuery query(*dbConnection());
        query.prepare(strSql);

        query.addBindValue(st.id);
        query.addBindValue(st.session_id);
        query.addBindValue(st.conditions);
        query.addBindValue(st.reply);
        query.addBindValue(st.is_hex);

        qDebug()<<"StTrigger:"<<strSql;
        exec(query);
    }

    return commit();
}

QVector<StTrigger> CTableTrigger::queryRows(QString strSessionId)
{
    QString strSql = QString("select * from %1 where session_id='%2'")
            .arg(m_strTableName,strSessionId);

    QSqlQuery query(*dbConnection());
    query.prepare(strSql);

    QVector<StTrigger> vecData;
    if(exec(query)){
        while(query.next()){
            QVariantList varList;
            for(int i = 0;i<query.record().count();i++){
                varList.append(query.value(i));
            }

            vecData.append(StTrigger().loadData(varList));
        }
    }

    return vecData;
}
